package com.sword.ehcache.common;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 公共工具
 * @author sword
 * @date 2020/10/9 17:25
 */
public class CommonUtil {
    /**
     * 获取本机的Ipv4地址
     * @return java.lang.String
     * @author sword
     * @date 2020/10/9 17:26
     */
    public static String getHostAddressIpv4() {
        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            // 如果网络接口为null则直接返回null
            if (networkInterfaces == null) {
                return null;
            }

            // 循环网络接口
            while (networkInterfaces.hasMoreElements()) {
                // 获取网络接口的所有网络地址
                Enumeration<InetAddress> inetAddresses = networkInterfaces.nextElement().getInetAddresses();

                // 循环网络地址
                while(inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    // 排除回环地址和不是Ipv4的地址
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        // 返回本机的Ipv4的地址
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        return null;
    }

}
